#include "query.h"
#include "ui_query.h"
#include "detail.h"
#include "../utility/connector.h"
#include "../data/company.h"
#include <QFileDialog>
#ifdef Q_OS_WINDOWS
#include <QAxObject>
#endif

Query::Query(QWidget *parent, Connector *connector) :
    QWidget(parent),connector(connector),
    ui(new Ui::Query) {
    qDebug()<<"Query::Query called.";
    ui->setupUi(this);
    entnameList=new QStringList;
    companyList=new QList<Company *>;
    //初始化数据成员
    pageCurr=0;
    pageTotal=0;
    //GUI内容清空，页码置零,清空Excel可选的路径
    ui->lineEdit_entname->clear();
    ui->comboBox_path->clear();
    //设置表格行数为0,清空内容

    //数据上屏bug 1：query最后的结果填满结果
    //Finished
    ui->tableWidget_result->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget_result->setRowCount(0);
    ui->tableWidget_result->clearContents();

    ui->label_currentpage->setText(QString::number(pageCurr));
    ui->label_count->setText(QString::number(pageTotal));
    connect(ui->comboBox_path, SIGNAL(currentIndexChanged(int)), this, SLOT(comboSelect(int)));

    connect(ui->pushButton_up,SIGNAL(clicked()),
            this,SLOT(pageUp()));
    connect(ui->pushButton_down,SIGNAL(clicked()),
            this,SLOT(pageDown()));
    connect(ui->pushButton_head,SIGNAL(clicked()),
            this,SLOT(pageHead()));
    connect(ui->pushButton_tail,SIGNAL(clicked()),
            this,SLOT(pageTail()));
    connect(ui->spinBox_page,SIGNAL(valueChanged(int)),
            this,SLOT(pageJump(int)));
    connect(ui->tableWidget_result,SIGNAL(cellClicked(int,int)),
            this,SLOT(showDetail(int,int)));
    connect(ui->lineEdit_entname,SIGNAL(editingFinished()),
            this,SLOT(singleQuery()));
    connect(ui->pushButton_selectFile,SIGNAL(clicked(bool)),
            this,SLOT(selectFile()));
    connect(ui->pushButton_batchQuery,SIGNAL(clicked(bool)),
            this,SLOT(batchQuery()));
    qDebug()<<"Query::Query returned.";
}

Query::~Query() {
    qDebug()<<"Query::~Query called.";
    for(Company *company:*companyList) delete company;
    delete companyList;
    delete entnameList;
    delete ui;
    qDebug()<<"Query::~Query returned.";
}

void Query::query() {
    qDebug()<<"Query::query called.";
    companyList->clear();
    connector->query(entnameList,25,pageCurr,&pageCurr,&pageTotal,companyList);
    /* TODO: [Done] 数据上屏
     * 数据：companyList,pageCurr,pageTotal
     */
    //清空表格，防止上一次结果比此次结果多，导致表格出错。
    ui->tableWidget_result->clearContents();
    for(int i=ui->tableWidget_result->rowCount()-1; i>=0; i--)
        ui->tableWidget_result->removeRow(i);
    //数据上屏
    QString str;
    ui->tableWidget_result->setRowCount(companyList->size());
    for(int i=0; i< companyList->size(); i++) {
        //序号+entname 如果序号未给定
        //str=QString::number(i);
        //ui->tableWidget_result->setItem(i,0,new QTableWidgetItem(str));
        str=*(companyList->value(i)->entname);
        ui->tableWidget_result->setItem(i,0,new QTableWidgetItem(str));
        ui->tableWidget_result->item(i,0)->setTextAlignment(Qt::AlignCenter);
        ui->tableWidget_result->setVerticalHeaderItem(i,new QTableWidgetItem(QString::number(i+(pageCurr-1)*25+1)));

        //tag
        for(int j=0; j<ui->tableWidget_result->columnCount()-1; j++) {
            str=companyList->value(i)->tag->value(j);
            QTableWidgetItem *item=new QTableWidgetItem(str);
            ui->tableWidget_result->setItem(i,1+j,item);
            ui->tableWidget_result->item(i,1+j)->setTextAlignment(Qt::AlignCenter);
        }
        ui->tableWidget_result->setItem(i,ui->tableWidget_result->columnCount()-1,new QTableWidgetItem("点击查看"));
        ui->tableWidget_result->item(i,ui->tableWidget_result->columnCount()-1)->setTextAlignment(Qt::AlignCenter);

    }
    ui->tableWidget_result->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
    ui->tableWidget_result->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
    ui->label_currentpage->setText(QString::number(pageCurr));
    ui->label_count->setText(QString::number(pageTotal));
    //m_mainTableWidget->resizeColumnToContents(6);
    //      m_mainTableWidget->update();
    qDebug()<<"Query::query returned.";
}

void Query::showDetail(int row, int column) {
    qDebug()<<"Query::showDetail called.";
    if(companyList->length()<row+1) {           //通过判断，如果点击的行的顺序数大于列表中的企业的数目，那么在该行的点击应该无效。
        qDebug()<<"Query::showDetail 无数据";
        return;
    }
    Detail *detail=new Detail(companyList->at(row));
    detail->show();
    qDebug()<<"Query::showDetail returned.";
}

void Query::singleQuery() {
    qDebug()<<"Query::singleQuery called.";
    /* TODO: [Done] 数据下屏
     * 数据：entnameList
     */
    QString str;
    str=ui->lineEdit_entname->text();
    if(str.isEmpty()) {
        qDebug()<<"Query::singleQuery noneed.";
        return;
    }
    //修改了entnameList的添加元素的方式，不能直接用entnameList.value(i)=XXXX的方式赋值
    //因为最开始这个List里面就空的，.value(i)本就是没有的
    //然后因为输入法的问题，中文，英文半角的逗号的分割都加上
    QStringList entname_list = str.split(",");
    entnameList->clear();
    for(int i=0; i<entname_list.size(); i++) {
        QStringList entname_tmp=entname_list.at(i).split("，");
        for(int j=0; j<entname_tmp.size(); j++)
            entnameList->append(entname_tmp.at(j));
    }
    query();
    qDebug()<<"Query::singleQuery returned.";
}

void Query::comboSelect(int) {
    qDebug()<<"Query::comboSelect called";
    QString strFile=ui->comboBox_path->currentText();
#ifdef Q_OS_WINDOWS
    //以下为使用strFile打开excel文件代码
    QAxObject excel("Excel.Application"); //加载Excel驱动
    excel.setProperty("Visible", false); //不显示Excel界面，如果为true会看到启动的Excel界面
    QAxObject* pWorkBooks = excel.querySubObject("WorkBooks");
    pWorkBooks->dynamicCall("Open (const QString&)", strFile);//打开指定文件
    QAxObject* pWorkBook = excel.querySubObject("ActiveWorkBook");
    QAxObject* pWorkSheet = pWorkBook->querySubObject("Sheets(int)", 1);
    QAxObject * usedrange = pWorkSheet->querySubObject("UsedRange");
    QAxObject * rows = usedrange->querySubObject("Rows");
    QAxObject * columns = usedrange->querySubObject("Columns");
    int rowStart = usedrange->property("Row").toInt();
    int colStart = usedrange->property("Column").toInt();
    int colsNum = columns->property("Count").toInt();
    int rowsNum = rows->property("Count").toInt();
    entnameList->clear();
    for (int i = rowStart; i < rowStart+rowsNum; i++) {
        for (int j = colStart; j< colStart+colsNum; j++) {
            QAxObject * cell = pWorkSheet->querySubObject("Cells(int,int)", i, j );
            if(cell->dynamicCall("Value2()").toString()!=NULL) {
                entnameList->append(cell->dynamicCall("Value2()").toString());
            }
        }
    }
    excel.dynamicCall("Quit(void)");
#else
    QFile file(strFile);
    file.open(QIODevice::ReadOnly | QIODevice::Text);
    entnameList->clear();
    while(!file.atEnd())
        entnameList->append(file.readLine().trimmed());
    file.close();
#endif
    //读取文件内容代码结束
    qDebug()<<"Query::comboSelect returned.";
}

void Query::selectFile() {
    qDebug()<<"Query::selectFile called.";
    /* TODO: [Done] 读取文件
     * 通过QFileDialog获取文件路径。
     * 在输入正确的情况下读取文件内容（每行一个企业名称），
     * 存入entnameList
     */
    QString strFile = QFileDialog::getOpenFileName(this,QStringLiteral("choose Excel"),"../",tr("Exel file(*.xls *.xlsx *.csv)"));
    if (strFile.isEmpty())
        return;
    if(ui->comboBox_path->findText(strFile)==-1)
        ui->comboBox_path->addItem(strFile);
    ui->comboBox_path->setCurrentText(strFile);
    //ui->lineEdit->setText(strFile);  //显示文件路径
#ifdef Q_OS_WINDOWS
    QAxObject excel("Excel.Application"); //加载Excel驱动
    excel.setProperty("Visible", false); //不显示Excel界面，如果为true会看到启动的Excel界面
    QAxObject* pWorkBooks = excel.querySubObject("WorkBooks");
    pWorkBooks->dynamicCall("Open (const QString&)", strFile);//打开指定文件
    QAxObject* pWorkBook = excel.querySubObject("ActiveWorkBook");
    QAxObject* pWorkSheet = pWorkBook->querySubObject("Sheets(int)", 1);
    QAxObject * usedrange = pWorkSheet->querySubObject("UsedRange");
    QAxObject * rows = usedrange->querySubObject("Rows");
    QAxObject * columns = usedrange->querySubObject("Columns");
    int rowStart = usedrange->property("Row").toInt();
    int colStart = usedrange->property("Column").toInt();
    int colsNum = columns->property("Count").toInt();
    int rowsNum = rows->property("Count").toInt();
    entnameList->clear();
    for (int i = rowStart; i < rowStart+rowsNum; i++) {
        for (int j = colStart; j< colStart+colsNum; j++) {
            QAxObject * cell = pWorkSheet->querySubObject("Cells(int,int)", i, j );
            if(cell->dynamicCall("Value2()").toString()!=NULL) {
                entnameList->append(cell->dynamicCall("Value2()").toString());
            }
        }
    }
    excel.dynamicCall("Quit(void)");
#else
    QFile file(strFile);
    file.open(QIODevice::ReadOnly | QIODevice::Text);
    entnameList->clear();
    while(!file.atEnd())
        entnameList->append(file.readLine().trimmed());
    file.close();
#endif
    qDebug()<<"Query::selectFile returned.";
}

void Query::batchQuery() {
    qDebug()<<"Query::batchQuery called.";
    query();
    qDebug()<<"Query::batchQuery returned.";
}

/* TODO: [Done] 翻页业务逻辑
 * 实现以下函数：
 * void pageHead();
 * void pageTail();
 * void pageUp();
 * void pageDown();
 * void pageJump(int);
 * 每个函数都应该是先更新数据成员的值，然后在数据无误的情况下调用filter()。
 */

void Query::pageHead() {
    qDebug()<<"Query::pageHead called.";
    if(pageTotal!=0) {
        pageCurr=1;
        query();
    } else {
        pageCurr=0;
    }
    qDebug()<<"Query::pageHead returned.";
}

void Query::pageTail() {
    qDebug()<<"Query::pageTail called.";
    if(pageTotal!=0) {
        pageCurr=pageTotal;
        query();
    } else {
        pageCurr=0;
    }
    qDebug()<<"Query::pageTail returned.";
}

void Query::pageUp() {
    qDebug()<<"Query::pageUp called.";
    if(pageTotal!=0) {
        pageCurr--;
        if(pageCurr < 1) {
            pageCurr=1;
        }
        query();
    } else {
        pageCurr=0;
    }
    qDebug()<<"Query::pageUp returned.";
}

void Query::pageDown() {
    qDebug()<<"Query::pageDown called.";
    if(pageTotal!=0) {
        pageCurr++;
        if(pageCurr > pageTotal) {
            pageCurr=pageTotal;
        }
        query();
    } else {
        pageCurr=0;
    }
    qDebug()<<"Query::pageDown returned.";
}

void Query::pageJump(int page) {
    qDebug()<<"Query::pageJump called.";
    if(pageTotal!=0) {
        if(page > pageTotal) {
            pageCurr=pageTotal;
        } else if(page < 1) {
            pageCurr=1;
        } else {
            pageCurr=page;
        }
        query();
    } else {
        pageCurr=0;
    }
    qDebug()<<"Query::pageJump returned.";
}
